Iterables are objects that can be iterated over, meaning you can loop through their elements. Common examples of iterables in JavaScript include arrays, strings, and sets.
Arrays are one of the most common iterables in JavaScript:
const array = [1, 2, 3, 4, 5];
for (let value of array) {
console.log(value);
}
// Outputs: 1 2 3 4 5
Strings are also iterables, allowing you to loop through each character:
const string = "Hello";
for (let char of string) {
console.log(char);
}
// Outputs: H e l l o
Sets are collections of unique values and can be iterated over:
const set = new Set([1, 2, 3, 4, 5]);
for (let value of set) {
console.log(value);
}
// Outputs: 1 2 3 4 5
You can create custom iterables by implementing the [Symbol.iterator]
method:
const customIterable = {
*Symbol.iterator {
yield 1;
yield 2;
yield 3;
}
};
for (let value of customIterable) {
console.log(value);
}
// Outputs: 1 2 3
Iterators are objects that provide a next()
method, which returns the next item in the sequence:
const array = [1, 2, 3];
const iterator = arraySymbol.iterator;
console.log(iterator.next()); // Outputs: { value: 1, done: false }
console.log(iterator.next()); // Outputs: { value: 2, done: false }
console.log(iterator.next()); // Outputs: { value: 3, done: false }
console.log(iterator.next()); // Outputs: { value: undefined, done: true }
The for...of
loop is a convenient way to iterate over iterables:
const array = [1, 2, 3, 4, 5];
for (let value of array) {
console.log(value);
}
// Outputs: 1 2 3 4 5